<template>
  <view>
    <view class="good-list">
      <view v-for="(goods, index) in goodsList" :key="index" @click="gotoDetail(goods)">
        <my-goods :goods='goods'></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj:{
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10
        },
        goodsList:[], // 商品列表的数据
        total: 0 ,// // 总数量，用来实现分页
        isloading: false
      };
    },
    onLoad(options) {
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
    },
    methods:{
      async getGoodsList(cb){
        this.isloading = true
        const {data:res} = await uni.$http.get('/goods/search', this.queryObj)
        this.isloading = false
        // 只要数据加载完毕，就立即按需加载 cb 回调函数
        cb && cb()
        if(res.meta.status !== 200) return uni.$showMsg()
        // console.log(res)
        this.goodsList = [...this.goodsList,...res.message.goods]
        this.total = res.message.total
      },
      gotoDetail(item){
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      }
    },
    // 上拉触底事件
    onReachBottom() {
      if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕！')
      
      if(this.isloading) return
      this.queryObj.pagenum++
      this.getGoodsList()
    },
    // 下拉刷新事件
    onPullDownRefresh() {
      // 重置数据
      this.queryObj.pagenum = 1
      this.goodsList = []
      this.total = 0
      this.isloading = false
      // 重新发起请求
      this.getGoodsList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">

</style>
